<template style="overflow: hidden;">
  <div class="container">
    <canvas :width="canvasWidth" :height="canvasHeight" ref="canvas" @mousedown="mousedown" @mousemove="mousemove"
      @mouseup="mouseup" @mouseout="mouseout" @touchstart="mousedown" @touchmove="mousemove" @touchend="mouseup"
      :style="{ backgroundColor: backgroundColor }">
      你的浏览器不支持canvas，快去升级浏览器吧！
    </canvas>
    <!-- 左边的侧边栏 -->
    <div class="sidebar" style="overflow: hidden">
      <div class="button" @click="switchPenType(0)">
        <img src="../assets/blackboard-mainbar/画笔.png" />
        <span>画笔</span>
      </div>
      <div class="button" @click="switchPenType(1)">
        <img src="../assets/blackboard-mainbar/橡皮.png" />
        <span>橡皮</span>
      </div>
      <div class="button" @click="popOut(0)">
        <img src="../assets/blackboard-mainbar/形状.png" />
        <span>形状</span>
      </div>
      <div class="button" @click="popOut(1)">
        <img src="../assets/blackboard-mainbar/笔触.png" />
        <span>笔触</span>
      </div>
      <div class="button" @click="popOut(2)">
        <img src="../assets/blackboard-mainbar/颜色.png" />
        <span>颜色</span>
      </div>
      <div class="button">
        <img src="../assets/blackboard-mainbar/文件.png" />
        <span>文件</span>
      </div>
      <div class="button" @click="switchPenType(7)">
        <img src="../assets/blackboard-popup/insert/文字.png" />
        <span>文字</span>
      </div>
      <div class="button" @click="undo()">
        <img src="../assets/blackboard-mainbar/撤回.png" />
        <span>撤回</span>
      </div>
    </div>
    <!-- 都写完了我才发现左右写反了...算了能用就行 -->
    <!-- 左下方功能球 -->
    <div class="bottomRightBar">
      <div class="button">
        <img src="../assets/上一页.png" @click="switchPage(-1)">
        <span>上一页</span>
      </div>
      <div>
        <p>{{ recentPage }}/{{ pageNumber }}</p>
        <p>页码</p>
      </div>
      <div class="button">
        <img src="../assets/下一页.png" @click="switchPage(1)">
        <span>下一页</span>
      </div>
    </div>
    <!-- 右下方功能球 -->
    <div class="bottomLeftBar">
      <div class="button">
        <img src="../assets/blackboard-mainbar/清除.png" @click="cleanAll()">
        <span>清除</span>
      </div>
      <div class="button">
        <img src="../assets/blackboard-mainbar/保存.png" @click="printCanvas()">
        <span>截图</span>
      </div>
      <div class="button">
        <img src="../assets/blackboard-mainbar/退出.png" @click="back()">
        <span>退出</span>
      </div>
    </div>
    <!-- 弹出框 -->
    <div class="pop" :style="{ display: popup.main }">
      <div :style="{ display: popup.shape }">
        <div class="button">
          <img src="../assets/blackboard-popup/shape/直线.png" @click="switchPenType(2)" />
          <span>直线</span>
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/shape/虚线.png" @click="switchPenType(3)" />
          <span>虚线</span>
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/shape/圆.png" @click="switchPenType(6)" />
          <span>圆</span>
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/shape/矩形.png" @click="switchPenType(5)" />
          <span>矩形</span>
        </div>
      </div>
      <div :style="{ display: popup.lineWidth }">
        <div class="button">
          <img src="../assets/blackboard-popup/lineWidth/大圆.png" @click="switchWidth(15, false)" />
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/lineWidth/中圆.png" @click="switchWidth(10, false)" />
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/lineWidth/小圆.png" @click="switchWidth(5, false)" />
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/lineWidth/小小圆.png" @click="switchWidth(1, false)" />
        </div>
      </div>
      <div :style="{ display: popup.color }">
        <div class="button">
          <img src="../assets/blackboard-popup/color/黑.png" @click="switchColor('black')" />
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/color/白.png" @click="switchColor('white')" />
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/color/红.png" @click="switchColor('red')" />
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/color/蓝.png" @click="switchColor('blue')" />
        </div>
      </div>
      <!-- <div :style="{display:popup.insert}">
        <div class="button">
          <img src="../assets/blackboard-popup/insert/文字.png" @click="switchPenType(7)"/>
          <span>文字</span>
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/insert/图片.png" @click="switchPenType(8)"/>
          <span>图片</span>
        </div>
        <div class="button">
          <img src="../assets/blackboard-popup/insert/文件.png" @click="switchPenType(2)"/>
          <span>文件</span>
        </div>
      </div> -->
    </div>
  </div>
  <centered-input ref="centerInput" v-on:keydown.enter.ctrl="showCenteredInput()" />
  <centered-image ref="centerImage" v-on:keydown.enter.ctrl="showCenteredImage()" />
  <alert-box ref="alert" />
  <a href="" ref="downloadLink" style="display: none;"></a>
</template>

<script setup>
import { onMounted, ref, onUnmounted, reactive, watch, inject } from "vue";
import html2canvas from "html2canvas";
import router from "@/router";
import centeredInput from '@/components/blackboard/centeredInput'
import alertBox from '@/components/blackboard/alertBox'
import centeredImage from '@/components/blackboard/centeredImage'
import { useWebsocket } from "../hooks";
import store from "@/store";
import { WS_ADDRESS } from "@/configs";

const msg = ref(false);
const canvas = ref(null);
var drawflag = false; //判断画笔状态
var context = null; //上下文
//坐标
var Xposition = null; //鼠标的x坐标
var Yposition = null; //鼠标的y坐标
var lastX = null; //鼠标先前的x坐标
var lastY = null; //鼠标先前的y坐标
var lineState = {
  lineWidth: 2, //线条粗细
  lineCap: "round", //端点形状 'round/butt/square':圆型/默认/方形
  strokeStyle: baseColor, //线条颜色
  lineJoin: "round", //相交点 'miter/round/bevel':默认/圆形/平直形式
}; //线条属性
var penType = {
  usePen: false, //判断是否使用画笔
  useEraser: false, //判断是否使用橡皮
  useLine: false, //判断是否使用直线
  useDashedLine: false, //判断是否使用虚线
  useArrow: false, //判断是否使用箭头
  useSquare: false, //判断是否使用矩形
  useCircle: false, //判断是否使用圆形
  useTextBox: false, //判断是否使用文本框
  useImageBox: false, //判断是否使用图片
};
var textState = {
  size: 20,
  font: "宋体",
  color: baseColor,
  textAlign: "left",
  textBaseline: "center",
}; //文字属性
var undoStack = []; //数据缓存
var downloadLink = ref(); //隐藏的下载链接
var recentPage = ref(1); //显示当前页数
var pageNumber = ref(1); //所有页数
var pageData = []; //存储每一页的内容
const backgroundColor = ref("black"); //黑板背景颜色
var baseColor = "white"; //画笔初始颜色
const canvasHeight = ref(500); //画布高度
const canvasWidth = ref(500); //画布宽度
const moreFunction = ref("none"); //更多功能
const popup = reactive({
  main: 'none',
  shape: 'none',
  lineWidth: 'none',
  color: 'none',
  insert: 'none',
})  //右侧弹出框
const centerInput = ref() //输入框
const alert = ref() //提示框
const centerImage = ref() //输入图片框
const socket = useWebsocket(handelMessage); //连接socket
const userData = store.state.userData
const roomData = store.state.roomData

onMounted(() => {
  //渲染上下文
  context = canvas.value.getContext("2d");
  //重置页数
  pageNumber.value = 1;
  recentPage.value = 1;
  //设置画布宽高
  canvasHeight.value = window.innerHeight;
  canvasWidth.value = window.innerWidth;
  pageData = [
    context.getImageData(0, 0, canvasWidth.value, canvasHeight.value),
  ];
  //设置初始笔画状态
  lineState = {
    lineWidth: 1,
    lineCap: "square",
    strokeStyle: baseColor,
    lineJoin: "bevel",
  };
  console.log('socket链接：' + WS_ADDRESS)
  setTimeout(() => {
    // console.log('socket状态', store.state.socketState)
    if (!store.state.socketState) {
      setTimeout(() => {
        alert.value.alertContent = 'WebSocket连接失败！请检查网络设置并重启页面！'
        alert.value.showAlert();
      }, 2000)
    }
  }, 2000)

});

//打开更多面板
function popOut(index) {
  console.log('打开更多面板')
  //清除打开状态
  popup.shape = 'none';
  popup.lineWidth = 'none';
  popup.color = 'none';
  popup.insert = 'none';
  //打开整体背景
  popup.main = 'flex';
  //打开部分背景
  switch (index) {
    case 0:
      popup.shape = 'flex';
      break;
    case 1:
      popup.lineWidth = 'flex';
      break;
    case 2:
      popup.color = 'flex';
      break;
    case 3:
      popup.insert = 'flex';
      break;
  }
}

//修改笔画类型
function switchPenType(type) {
  console.log("switchPenType", type);
  //在页面上画一个背景 
  if (msg.value) {
    eraser(1, 0, 0)
    eraser(2, canvasWidth.value, canvasHeight.value)
  }
  msg.value = false
  //清除所有笔画状态
  Object.keys(penType).forEach(function (key) {
    penType[key] = false;
  });
  //重置笔画状态
  lineState = {
    lineWidth: 1,
    lineCap: "round",
    strokeStyle: baseColor,
    lineJoin: "round",
  };
  context.setLineDash([0, 0]);
  //关闭功能球
  popup.main = 'none';
  //修改笔画状态
  switch (type) {
    case 0: //画笔
      penType.usePen = true;
      break;
    case 1: //橡皮
      penType.useEraser = true;
      break;
    case 2: //直线
      penType.useLine = true;
      break;
    case 3: //虚线
      penType.useDashedLine = true;
      break;
    // case 4: //箭头
    //   arrow();
    //   penType.useArrow = true;
    //   break;
    case 5: //矩形
      penType.useSquare = true;
      break;
    case 6: //圆形
      penType.useCircle = true;
      break;
    case 7: //文本框
      penType.useTextBox = true;
      //显示提示框 
      if (alert.value) {
        alert.value.alertContent = '请选择文本所在的位置'
        alert.value.showAlert();
      }
      break;
    case 8: //图片
      penType.useImageBox = true;
      //显示提示框
      alert.value.alertContent = '请选择图片所在的位置'
      alert.value.showAlert()
      break;
  }
}

//按下鼠标
function mousedown() {
  if (penType.usePen) {
    pen(1);
  } else if (penType.useEraser) {
    eraser(1);
  } else if (penType.useLine) {
    line(1);
  } else if (penType.useDashedLine) {
    dashedLine(1);
  } else if (penType.useSquare) {
    square(1);
  } else if (penType.useCircle) {
    circle(1);
  } else if (penType.useTextBox) {
    textBox(1);
  } else if (penType.useImageBox) {
    //反正和文本框的方法一样，就不多写那几行了
    textBox(1);
  }
}

//移动鼠标
function mousemove() {
  if (penType.usePen) {
    pen(2);
  } else if (penType.useEraser) {
    eraser(2);
  }
}

//抬起鼠标
function mouseup() {
  save();
  if (penType.usePen) {
    pen(3);
  } else if (penType.useEraser) {
    eraser(3);
  } else if (penType.useLine) {
    line(3);
  } else if (penType.useDashedLine) {
    dashedLine(3);
  } else if (penType.useSquare) {
    square(3);
  } else if (penType.useCircle) {
    circle(3);
  } else if (penType.useTextBox) {
    textBox(3);
  } else if (penType.useImageBox) {
    drawflag = false;
    showCenteredImage();
  }
}

//鼠标离开画板
function mouseout() {
  save();
  if (penType.usePen) {
    pen(3);
  } else if (penType.useEraser) {
    eraser(3);
  } else if (penType.useLine) {
    line(4);
  } else if (penType.useDashedLine) {
    dashedLine(4);
  } else if (penType.useSquare) {
    square(4);
  } else if (penType.useCircle) {
    circle(4);
  }
}

//画笔相关
function pen(stage, Xremote, Yremote) { //后两变量为远端获取的坐标,后同
  switch (stage) {
    case 1: //鼠标按下，后同
      //修改绘画状态
      drawflag = true;
      //开始绘画
      context.beginPath();
      //重置线条属性
      context.lineWidth = lineState.lineWidth;
      context.lineCap = lineState.lineCap;
      context.strokeStyle = lineState.strokeStyle;
      context.lineJoin = lineState.lineJoin;
      //获取起始坐标
      getPosition();
      //设定画笔的起始点
      //如果没有远端信息就用前边获取的坐标
      if (Xremote && Yremote) {
        context.moveTo(Xremote, Yremote);
      } else {
        context.moveTo(Xposition, Yposition);
        //发送起始点坐标
        sendStartLocation('pen')
      }
      break;
    case 2: //鼠标移动
      if (!drawflag) break;
      //获取新的坐标
      getPosition();
      //绘制路径
      //如果没有远端信息就用前边获取的坐标
      if (Xremote && Yremote) {
        context.lineTo(Xremote, Yremote);
      } else {
        context.lineTo(Xposition, Yposition);
        //发送路径点坐标
        sendPointLocation('pen');
      }
      context.stroke();
      break;
    case 3: //鼠标抬起&鼠标移出画板
      drawflag = false;
      sendEndMessage();
      break;
  }
}

//橡皮相关
function eraser(stage, Xremote, Yremote) {
  switch (stage) {
    case 1:
      drawflag = true;
      //设置虚线偏移量
      context.setLineDash([0, 0]);
      //获取起始坐标
      getPosition();
      if (Xremote && Yremote) {
        lastX = Xremote;
        lastY = Yremote;
      } else {
        lastX = Xposition;
        lastY = Yposition;
        //发送起始点坐标
        sendStartLocation('eraser')
      }
      break;
    case 2:
      if (!drawflag) break;
      //获取新坐标
      getPosition();
      context.beginPath();
      //画一个新矩形盖住原来的笔迹
      if (Xremote && Yremote) {
        context.rect(lastX, lastY, Xremote - lastX, Yremote - lastY);
      } else {
        context.rect(lastX, lastY, Xposition - lastX, Yposition - lastY);
        //发送路径点坐标
        sendPointLocation('eraser');
      }
      context.fillStyle = backgroundColor.value;
      context.fill();
      break;
    case 3:
      sendEndMessage();
      drawflag = false;
      break;
  }
}

//直线相关
function line(stage, Xremote, Yremote) {
  switch (stage) {
    case 1:
      drawflag = true;
      //获取起始坐标
      getPosition();
      if (Xremote && Yremote) {
        context.moveTo(Xremote, Yremote);
      } else {
        //设定画笔的起始点
        context.moveTo(Xposition, Yposition);
        sendStartLocation('line')
      }
      break;
    case 3:
      getPosition();
      if (Xremote && Yremote) {
        context.lineTo(Xremote, Yremote);
      } else {
        context.lineTo(Xposition, Yposition);
        sendPointLocation('line')
      }
      context.stroke();
    case 4:
      sendEndMessage();
      drawflag = false;
      break;
  }
}

//虚线相关
function dashedLine(stage, Xremote, Yremote) {
  switch (stage) {
    case 1:
      drawflag = true;
      //设置虚线偏移量
      context.setLineDash([10, 10]);
      context.beginPath();
      getPosition();
      if (Xremote && Yremote) {
        context.moveTo(Xremote, Yremote);
      } else {
        //设定画笔的起始点
        context.moveTo(Xposition, Yposition);
        sendStartLocation('dashedLine')
      }
      break;
    case 3:
      getPosition();
      if (Xremote && Yremote) {
        context.lineTo(Xremote, Yremote);
      } else {
        context.lineTo(Xposition, Yposition);
        sendPointLocation('dashedLine')
      }
      context.stroke();
    case 4:
      sendEndMessage();
      drawflag = false;
  }
}

//矩形相关
function square(stage, Xremote, Yremote) {
  switch (stage) {
    case 1:
      drawflag = true;
      //获取起始坐标
      getPosition();
      //设定画笔的起始点
      if (Xremote && Yremote) {
        lastX = Xremote;
        lastY = Yremote;
      } else {
        lastX = Xposition;
        lastY = Yposition;
        //发送起始点坐标
        sendStartLocation('square')
      }
      break;
    case 3:
      //获取终点坐标
      getPosition();
      //描边
      context.strokeStyle = lineState.strokeStyle; // 黑色描边
      context.lineWidth = lineState.lineWidth; // 设置描边宽度
      context.beginPath();
      if (Xremote && Yremote) {
        context.rect(lastX, lastY, Xremote - lastX, Yremote - lastY);
      } else {
        context.rect(lastX, lastY, Xposition - lastX, Yposition - lastY);
        //发送路径点坐标
        sendPointLocation('square');
      }
      context.stroke();
    // 描边路径
    case 4:
      drawflag = false;
      break;
  }
}

//椭圆相关
function circle(stage, Xremote, Yremote) {
  switch (stage) {
    case 1:
      drawflag = true;
      //设置描边
      context.lineWidth = lineState.lineWidth;
      context.strokeStyle = lineState.strokeStyle;
      context.beginPath();
      getPosition();
      //设定画笔的起始点
      if (Xremote && Yremote) {
        lastX = Xremote;
        lastY = Yremote;
      } else {
        lastX = Xposition;
        lastY = Yposition;
        //发送起始点坐标
        sendStartLocation('circle')
      }
      break;
    case 3:
      getPosition();
      if (Xremote && Yremote) {
        Xposition = Xremote
        Yposition = Yremote
      } else {
        sendPointLocation('circle')
      }
      const x = (Xposition + lastX) / 2;
      const y = (Yposition + lastY) / 2;
      const radius = Math.abs((Xposition - lastX) / 2);
      //绘制路径
      context.arc(x, y, radius, 0, 2 * Math.PI);
      // 描边路径
      context.stroke();
    case 4:
      sendEndMessage();
      drawflag = false;
      break;
  }
}

//文本框相关
function textBox(stage, Xremote, Yremote, msg) {
  switch (stage) {
    case 1:
      drawflag = true;
      //获取起始坐标
      getPosition();
      break;
    case 3:
      drawflag = false;
      //显示文本框
      showCenteredInput();
      break;
    case 5: //输入文本后按下确认
      // 设置文本属性
      context.font = textState.size + "px " + textState.font;
      context.fillStyle = textState.color;
      context.textAlign = textState.textAlign;
      context.textBaseline = textState.textBaseline;
      // 添加文本到画布
      if (Xremote && Yremote && msg) {
        context.fillText(msg, Xremote, Yremote);
        return;
      } else {
        context.fillText(centerInput.value.inputValue, Xposition, Yposition);
        socket.send(JSON.stringify({
          type: 'textBox',
          x: Xposition,
          y: Yposition,
          msg: centerInput.value.inputValue,
          userId: userData.userId,
          roomId: roomData.roomId,
        }))
        centerInput.value.inputValue = ''
      }
      break;
  }
}

//图片相关
function chooseImage() {
  drawflag = false;
  //提取文件
  const file = centerImage.value.imageFile;
  var fileUrl = null;
  var fileWidth = null;
  var fileHeight = null;
  if (file) {
    //创建url
    fileUrl = dataURItoBlob(URL.createObjectURL(file));
    console.log(typeof (fileUrl))
    //获得图片大小
    const reader = new FileReader();
    reader.onload = (event) => {
      const img = new Image();
      img.onload = () => {
        fileHeight = img.height;
        fileWidth = img.width;
      };
      img.src = event.target.result;
    };
    reader.readAsDataURL(fileUrl);
    context.drawImage(
      img,
      Xposition,
      Yposition,
      Xposition + img.width,
      Yposition + img.height
    );
  }
}

//把string类型转为blob类型
function dataURItoBlob(dataURI) {
  // 将base64解码  
  var byteString = atob(dataURI.split(',')[1]);

  // 获取mime类型  
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // 写入数组缓冲区  
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  // 创建Blob对象  
  return new Blob([ab], { type: mimeString });
}

//上一页和下一页
function switchPage(number, flag) {
  const newPageNumber = recentPage.value + number;
  //如果到了第一页
  if (newPageNumber <= 0) {
    alert.value.alertContent = '已经是第一页了喔'
    alert.value.showAlert();
    return;
  }
  if (flag == undefined) {
    //发送翻页请求
    socket.send(JSON.stringify({
      type: 'switchPage',
      userId: userData.userId,
      roomId: roomData.roomId,
      number: number
    }))
  }
  //清除撤销堆栈
  undoStack = [];
  //保存文件
  save();
  pageData[recentPage.value - 1] = undoStack[undoStack.length - 1];
  //新建页面
  if (newPageNumber > pageNumber.value) {
    console.log("create new page");
    //清空页面
    cleanAll();
    //在pageData中加入新元素
    pageData.push("");
    //修改pageNumber数据
    pageNumber.value++;
  }
  //跳转到旧的页面
  else {
    console.log("skip to old page");
    //获得旧页面的数据
    const oldPageData = pageData[newPageNumber - 1];
    //把旧页面的数据烧录到画板上
    context.putImageData(oldPageData, 0, 0);
  }
  //修改recentPage数据
  recentPage.value = newPageNumber;
}

//修改颜色
function switchColor(color, flag) {
  //关闭功能球
  popup.main = 'none';
  //修改颜色
  lineState.strokeStyle = color;
  textState.color = color;
  console.log("修改颜色成功！" + lineState.strokeStyle);
  //发送信息
  if (flag) {
    return;
  }
  socket.send(JSON.stringify({
    type: 'color',
    userId: userData.userId,
    roomId: roomData.roomId,
    color: color
  }))
}

//修改线条粗细
function switchWidth(number, flag) {
  //关闭功能球
  popup.main = 'none';
  var newWidth = number;
  var newSize = number;
  if (newWidth > 0) {
    lineState.lineWidth = newWidth;
    textState.size = newSize;
    console.log("修改线条粗细成功！", lineState.lineWidth);
    console.log("修改字体大小成功！", textState.size);
    if (flag) {
      return;
    }
    socket.send(JSON.stringify({
      type: 'lineWidth',
      userId: userData.userId,
      roomId: roomData.roomId,
      number: number
    }))
  } else {
    console.error("线条太细了！");
  }
}

//修改对齐方式
function switchTextAlign(number) {
  switch (number) {
    case 1:
      textState.textAlign = "left";
      break;
    case 2:
      textState.textAlign = "center";
      break;
    case 3:
      textState.textAlign = "right";
      break;
  }
}

//保存canvas状态
function save() {
  //获取当前页面
  const imageData = context.getImageData(
    0,
    0,
    canvasWidth.value,
    canvasHeight.value
  );
  //把当前canvas状态推入撤销堆栈
  if (imageData) {
    undoStack.push(imageData);
  }
}

//撤销
function undo() {
  if (undoStack.length > 0) {
    var imgData = undoStack.pop();
    context.putImageData(imgData, 0, 0);
  }
}

//获取鼠标坐标
function getPosition() {
  Xposition = event.offsetX;
  Yposition = event.offsetY;
}

//清除所有笔迹
function cleanAll(flag) {
  context.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  if (flag == undefined) {
    socket.send(JSON.stringify({
      type: 'cleanAll',
      userId: userData.userId,
      roomId: roomData.roomId,
    }))
  }
}

//截图
async function printCanvas() {
  save();
  if (undoStack.length == 0) {
    alert("图都是空白的要保存个啥？");
    return;
  }
  try {
    if (canvas.value && canvas.value.toDataURL) {
      // 创建一个新的 canvas，与原始 canvas 尺寸相同  
      const newCanvas = document.createElement('canvas');
      newCanvas.width = canvas.value.width;
      newCanvas.height = canvas.value.height;
      const ctxNew = newCanvas.getContext('2d');
      // 在新 canvas 上绘制背景颜色  
      ctxNew.fillStyle = backgroundColor.value; // 假设背景颜色为白色  
      ctxNew.fillRect(0, 0, newCanvas.width, newCanvas.height);
      // 将原始 canvas 的内容绘制到新 canvas 上  
      ctxNew.drawImage(canvas.value, 0, 0);

      // 将canvas内容转换为DataURL  
      const dataURL = await newCanvas.toDataURL('image/png');
      // 创建一个a标签用于下载  
      downloadLink.value.href = dataURL;
      downloadLink.value.download = 'canvas-page' + recentPage.value + '.png'; // 设置下载文件名  
      // 触发点击事件   
      downloadLink.value.click();
    }
  } catch (error) {
    console.error("截图失败：", error);
    alert("截图失败！");
  }
}

//返回主页
function back() {
  router.push("/");
}

//显示和隐藏输入框
function showCenteredInput() {
  centerInput.value.show();
  if (centerInput.value.inputValue) {
    textBox(5, 0, 0, '');
    switchPenType(0);
  }
}

//显示和隐藏输入图片框
function showCenteredImage() {
  centerImage.value.show();
  if (!centerImage.value.showInput) {
    chooseImage();
  }
}

//修改背景颜色
function changeBackgroundColor() {
  baseColor = baseColor == 'black' ? 'white' : 'black'
  backgroundColor.value = backgroundColor.value == 'white' ? 'black' : 'white'
  console.log('背景颜色修改成功！', backgroundColor.value)
  console.log('初始颜色修改成功！', baseColor)
}

//获取socket消息
function handelMessage(event) {
  const data = JSON.parse(event.data);
  //防止用户重复收到消息
  if (userData.userId == data.userId && roomData.roomId == data.roomId) {
    return;
  }
  // console.log('socket发送的' + data.type, data);
  switch (data.type) {
    case 'startLocation': //起始坐标
      switch (data.penType) { //使用画笔
        case 'pen':
          if (!penType.usePen) {
            switchPenType(0);
          }
          pen(1, data.x, data.y)
          break;
        case 'eraser':
          if (!penType.useEraser) {
            switchPenType(1);
          }
          eraser(1, data.x, data.y)
          break;
        case 'line':
          if (!penType.useLine) {
            switchPenType(2)
          }
          line(1, data.x, data.y)
          break;
        case 'dashedLine':
          if (!penType.useDashedLine) {
            switchPenType(3)
          }
          context.setLineDash([10, 10]);
          dashedLine(1, data.x, data.y)
          break;
        case 'square':
          if (!penType.useSquare) {
            switchPenType(5)
          }
          square(1, data.x, data.y)
          break;
        case 'circle':
          if (!penType.useCircle) {
            switchPenType(6);
          }
          circle(1, data.x, data.y)
          break;
      }
      break;
    case 'pathPointLocation': //路径点坐标
      switch (data.penType) { //使用画笔
        case 'pen':
          if (!penType.usePen) {
            switchPenType(0);
          }
          pen(2, data.x, data.y)
          break;
        case 'eraser':
          if (!penType.useEraser) {
            switchPenType(1);
          }
          eraser(2, data.x, data.y)
          break;
        case 'line':
          if (!penType.useLine) {
            switchPenType(2)
          }
          line(3, data.x, data.y)
          break;
        case 'dashedLine':
          if (!penType.useDashedLine) {
            switchPenType(3)
          }
          context.setLineDash([10, 10]);
          dashedLine(3, data.x, data.y)
          break;
        case 'square':
          if (!penType.useSquare) {
            switchPenType(5)
          }
          square(3, data.x, data.y)
          break;
        case 'circle':
          if (!penType.useCircle) {
            switchPenType(6);
          }
          circle(3, data.x, data.y)
          break;
      }
      break;
    case 'stopDrawing': //结束绘画
      // switchPenType(10086)
      drawflag = false;
      break;
    case 'textBox':
      // switchPenType(7);
      textBox(5, data.x, data.y, data.msg);
      break;
    case 'cleanAll':
      cleanAll(true);
      break;
    case 'color':
      switchColor(data.color, true);
      break;
    case 'lineWidth':
      switchWidth(data.number, true);
      break;
    case 'switchPage':
      switchPage(data.number, true);
      break;
  }
}

//发送起始点坐标
function sendStartLocation(type) {
  socket.send(JSON.stringify({
    type: 'startLocation',
    x: Xposition,
    y: Yposition,
    userId: userData.userId,
    roomId: roomData.roomId,
    penType: type
  }))
}

//发送路径点坐标
function sendPointLocation(type) {
  socket.send(JSON.stringify({
    type: 'pathPointLocation',
    x: Xposition,
    y: Yposition,
    userId: userData.userId,
    roomId: roomData.roomId,
    penType: type
  }))
}

//发送结束信号
function sendEndMessage() {
  socket.send(JSON.stringify({
    type: 'stopDrawing',
    userId: userData.userId,
    roomId: roomData.roomId,
  }))
}

defineExpose({
  changeBackgroundColor
})
</script>

<style scoped>
* {
  margin: 0px;
  padding: 0px;
}

canvas {
  overflow: hidden;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

.sidebar {
  padding: 5px 0 5px 0;
  width: 2.5rem;
  height: auto;
  position: absolute;
  right: 1.25rem;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 10px;
  background-color: rgb(232, 232, 232);
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: center;
}

.button {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 5px 0px 5px 0px;
}

.button img {
  height: 0.9375rem;
  width: auto;
}

span {
  margin-top: 2.5px;
  font-size: 0.5rem;
}

.container {
  overflow: hidden;
}

.bottomRightBar {
  width: 15rem;
  height: 4.5rem;
  position: absolute;
  left: 2rem;
  bottom: 1.5rem;
  background-color: rgb(232, 232, 232);
  border-radius: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.bottomRightBar .button {
  width: 8rem;
  height: auto;
  cursor: pointer;
}

.bottomRightBar div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: default;
}

.bottomRightBar p {
  width: 4rem;
  height: auto;
  font-weight: bolder;
  font-size: 1rem;
  text-align: center;
}

.bottomRightBar .button img {
  width: 1rem;
  height: auto;
}

.bottomLeftBar {
  width: 12rem;
  height: 4.5rem;
  position: absolute;
  right: 2rem;
  bottom: 1.5rem;
  background-color: rgb(232, 232, 232);
  border-radius: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.bottomLeftBar .button {
  width: 4rem;
  height: auto;
}

.bottomLeftBar .button img {
  width: 2rem;
  height: auto;
}

.button {
  cursor: pointer;
}

.pop {
  width: 8rem;
  height: 2.5rem;
  background-color: rgb(232, 232, 232);
  border-radius: 10px;
  z-index: 100;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 4rem;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.pop .button {
  width: 2rem;
  height: auto;
}

.pop .button img {
  width: 1rem;
  height: auto;
}
</style>